<?php
	session_start();
	$page= "Admin";
	$message = null;
	include ('includes/header.php');
	include('includes/menubar.php');
	require('config/mysql.config.inc');
	
	function isValidEntry($value){
		$pattern = "/^([a-zA-Z0-9\s\.\!\?]+)$/";
		return preg_match($pattern, $value);
	}
	//CONNECT TO DB
	$mysqli = new mysqli($host, $username, $password, $db);	
?>

<div class="body_content">

<?php
//ADDING A NEW ENTRY TO A SIMPLE TABLE
if(isset($_POST['newcattype']) || isset($_POST['newfintype']) || isset($_POST['newmattype']) || isset($_POST['newshapetype']) || isset($_POST['newtype'])){
	if(isset($_POST['newcattype'])){$simpletable = "CategoryTypes"; $val = $_POST['newcattype']; $name = "cname";}
	if(isset($_POST['newfintype'])){$simpletable = "FinishTypes"; $val = $_POST['newfintype']; $name = "fname";}
	if(isset($_POST['newmattype'])){$simpletable = "MaterialTypes"; $val = $_POST['newmattype']; $name = "mname";}
	if(isset($_POST['newshapetype'])){$simpletable = "ShapeTypes"; $val = $_POST['newshapetype']; $name = "sname";}
	if(isset($_POST['newtype'])){$simpletable = "Types"; $val = $_POST['newtype']; $name = "tname";}
	
}
if (isset($simpletable) && isset($val) && isset($name)) { 	
	if($val != "" && isValidEntry($val)){
		$new = htmlentities($val);
		$query = "SELECT * FROM " .  $simpletable . " WHERE " . $name . " = '" . $new . "';";
		$result = $mysqli->query($query);
		if($result->num_rows == 0){
			$query = "INSERT into " . $simpletable . " (" . $name . ") VALUES ('" . $new ."')";
			$result = $mysqli->query($query);
			if(!$result){
				$message = $message . "Error Message: Database Error.";
			}
			else{
				$message = $message . "Message: " . $new . " was successfully created.\n <br/>";
			}
		}
		else{
			$message = $message . "Error Message: Name already exists.\n <br/>";	
		}	
	}
	else{
		$message = $message . "Error Message: Not a valid entry.\n <br/>";
	}
}

//DELETING AN ENTRY FROM A SIMPLE TABLE
if(isset($_POST['deletecattype']) || isset($_POST['deletefintype']) || isset($_POST['deletemattype']) || isset($_POST['deleteshapetype'])){
	if(isset($_POST['deletecattype'])){$delsimpletable = "CategoryTypes"; $delval = $_POST['deletecattype']; $delname = "cname"; $str = "categoryid";}
	if(isset($_POST['deletefintype'])){$delsimpletable = "FinishTypes"; $delval = $_POST['deletefintype']; $delname = "fname"; $str = "finishid";}
	if(isset($_POST['deletemattype'])){$delsimpletable = "MaterialTypes"; $delval = $_POST['deletemattype']; $delname = "mname"; $str = "materialid";}
	if(isset($_POST['deleteshapetype'])){$delsimpletable = "ShapeTypes"; $delval = $_POST['deleteshapetype']; $delname = "sname"; $str = "shapeid";}
	if(isset($_POST['deletetype'])){$delsimpletable = "Types"; $delval = $_POST['deletetype']; $delname = "tname"; $str = "typeid";}
	
}
if (isset($delsimpletable) && isset($delval) && isset($delname)) {
	$delete = htmlentities($delval);
	$query = "SELECT ". $str . " FROM ". $delsimpletable . " WHERE " . $delname . " = '" . $delval . "';";
	$result = $mysqli->query($query);
	if($result->num_rows == 0){
		$message = $message . "Error Message: Database Error";
	}
	else{
		$ans = $result->fetch_assoc();
		$id = $ans[$str];
		$query = "DELETE FROM " . $delsimpletable . " WHERE " . $str . " = '" . $id . "';";
		$result = $mysqli->query($query);
		if(!$result){
			$message = $message . "Error Message: Database Error";
		}
		else{
			$message = $message . " " . $delval . " was successfully deleted.\n <br/>";
		}
	}
}

//IF ADD SET
if(isset($_POST['newsetcategorytype']) && isset($_POST['newsetname'])){
	$setname = htmlentities($_POST['newsetname']);
	$categoryid = getIDNumber("CategoryTypes", htmlentities($_POST['newsetcategorytype']));
	$query = "SELECT * FROM Sets WHERE setname = '" . $setname . "';";
	$result = $mysqli->query($query);
	if($result->num_rows == 0){
		$query = "INSERT into Sets (categoryid, setname) VALUES ('" . $categoryid ."' , '" . $setname . "')";
		$result = $mysqli->query($query);
		if(!$result){
			$message = $message . "Error Message: Database Error";
		}
		else{
			$message = $message . "Message: " . $setname . " was successfully created.\n <br/>";
		}
	}
	else{
		$message = $message . "Error Message: Name already exists.\n <br/>";	
	}	
}


	
//IF DELETE SET
if(isset($_POST['deleteset'])){
	$setname = htmlentities($_POST['deleteset']);
	$query = "SELECT * FROM Sets WHERE setname = '" . $setname . "';";
	$result = $mysqli->query($query);
	if($result->num_rows == 0){
		printf("Error Message: %s\n <br/>", $mysqli->error);
	}
	else{
		$ans = $result->fetch_assoc();
		$setid = $ans["setid"];
		$query = "DELETE FROM Sets WHERE setid = '" . $setid . "';";
		$result = $mysqli->query($query);
		if(!$result){
			$message = $message . "Error Message: Database Error";
		}
		else{
			$message =  $message . "Set was successfully deleted.\n <br/>";
		}
	}	
}

//IF ADDING PIECE TO SET
if(isset($_POST['modifysettype']) && isset($_POST['addpiecetoset'])){
	$setmod = htmlentities($_POST['modifysettype']);
	$piecetoad = htmlentities($_POST['addpiecetoset']);
	$setmodid = getIDNumber("Sets", $setmod);
	$piecetoadID = getIDNumber("Pieces", $piecetoad);
	$query = "INSERT into InSet (setid, modelno) values ('" . $setmodid . "' , ' " . $piecetoadID . "')";
	$result = $mysqli->query($query);
	if(!$result){
		$message = $message . "Error Message: Database Error";
	}
	else{
		$message = $message . "Piece successfully added to set!";
	}
}

//Function: Takes a table name, and an item name that would be in that table and returns to you the primarykey(id) corresponding to that item name
//Purpose: this will save time later because through post variables I can only get names, not id numbers.
function getIDNumber($tablename, $itemname){
	require('config/mysql.config.inc');
	$mysqli = new mysqli($host, $username, $password, $db);	
	
	if($tablename == "CategoryTypes"){$idname = "categoryid"; $name = "cname";}
	if($tablename == "FinishTypes"){$idname = "finishid"; $name = "fname";}
	if($tablename == "ShapeTypes"){$idname = "shapeid"; $name = "sname";}
	if($tablename == "MaterialTypes") {$idname = "materialid"; $name = "mname";}
	if($tablename == "Sets") {$idname = "setid"; $name = "setname";}
	if($tablename == "Pieces") {$idname = "modelno"; $name = "pname";}
	if($tablename == "Types") {$idname = "typeid"; $name = "tname";}
	
	if(isset($idname)){
		$result = $mysqli->query("SELECT " . $idname . " FROM ". $tablename . " WHERE " . $name . " = '" . $itemname . "'");
		if($result->num_rows != 0){
			$ans = $result->fetch_assoc();
			$id = $ans[$idname];
			return $id;
		}
		else{
			printf("No results!");
			
		}	
	}
	else{
		$message += "This function doesn't work with this table\n";
	}
	
}


if(isset($_POST['newpiecename']) && isset($_POST['newpiecemodelno']) && isset($_POST['newpiecedescription']) && isset($_POST['newpiecephotourl'])){
	$modelno = htmlentities($_POST['newpiecemodelno']);
	$name = htmlentities($_POST['newpiecename']);
	$description = htmlentities($_POST['newpiecedescription']);
	$photourl = htmlentities($_POST['newpiecephotourl']);
	$newpiececattype = htmlentities($_POST['newpiececategorytype']);
	$newpiecemattype = htmlentities($_POST['newpiecematerialtype']);
	$newpieceshapetype = htmlentities($_POST['newpieceshapetype']);
	$newpiecefinishtype = htmlentities($_POST['newpiecefinishtype']);
	$newpiecetype = htmlentities($_POST['newpiecetype']);
	$newpieceheight = explode(" ", htmlentities($_POST['newpieceheight']));
	$newpiecewidth = explode(" ", htmlentities($_POST['newpiecewidth']));
	$newpiecelength = explode(" ", htmlentities($_POST['newpiecelength']));
	
	
	$query = "SELECT * FROM Pieces WHERE modelno = '" . $modelno . "';";
	$result = $mysqli->query($query);
	if($result->num_rows == 0){
		//okay to add
		//TODO: FINISH THIS SO WE GET MORE INFORMATION INTO THE DB FOR EACH PIECE
		$categoryid = getIDNumber("CategoryTypes", $newpiececattype);
		$finishid = getIDNumber("FinishTypes", $newpiecefinishtype);
		$materialid = getIDNumber("MaterialTypes", $newpiecemattype);
		$shapeid = getIDNumber("ShapeTypes", $newpieceshapetype);
		$query = "INSERT into Pieces (modelno, pname, description, photourl, categoryid, finishid, materialid, shapeid, length, width, height, typeid) VALUES ('" . $modelno ."', '" . $name . "', '" . $description . "', '" . $photourl . "' , '" . $categoryid . "', '" . $finishid . "' , '" . $materialid . "' , '" . $shapeid . "', '" . $newpiecelength[0] . "', '" . $newpiecewidth[0] . "', '" . $newpieceheight[0] . "', '" . $newpiecetype . "')";
			$result = $mysqli->query($query);
			if(!$result){
				$message = $message . "Error Message: Database Error";
			}
			else{
				$message = $message . "New piece successfully added!";
			}
	} else {
		$message =  $message. "A piece with that model number already exists!";
	}
	
}

?>

	
	<h3>Add/Remove Categories</h3>
	<form action="admin.php" method="post">
		New Category Name: <input type="text" name="newcattype" />
		<input type="submit" value="Create Category" /><br /><br />	
	</form>
			
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM CategoryTypes ORDER BY categoryid");
			print("<select name=\"deletecattype\">");
			if($result->num_rows == 0){
				print "Error: No Category Types. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($cattype = $result->fetch_assoc()){
					$i++;
					print "<option>" . $cattype["cname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete Category" />
	</form>
	
	
	<h3>Add/Remove Finishes</h3>
	<form action="admin.php" method="post">
		New Finish Name: <input type="text" name="newfintype" />
		<input type="submit" value="Create Finish" /><br /><br />	
	</form>
			
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM FinishTypes ORDER BY finishid");
			print("<select name=\"deletefintype\">");
			if($result->num_rows == 0){
				print "Error: No Finish Types. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($fintype = $result->fetch_assoc()){
					$i++;
					print "<option>" . $fintype["fname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete FinishType" />
	</form>
	
	
	<h3>Add/Remove Materials</h3>
	<form action="admin.php" method="post">
		New Material Name: <input type="text" name="newmattype" />
		<input type="submit" value="Create Material" /><br /><br />	
	</form>
			
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM MaterialTypes ORDER BY materialid");
			print("<select name=\"deletemattype\">");
			if($result->num_rows == 0){
				print "Error: No Material Types. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($mattype = $result->fetch_assoc()){
					$i++;
					print "<option>" . $mattype["mname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete Material" />
	</form>
	
	<h3>Add/Remove Types</h3>
	<form action="admin.php" method="post">
		New Type Name: <input type="text" name="newtype" />
		<input type="submit" value="Create Type" /><br /><br />	
	</form>
			
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM Types ORDER BY typeid");
			print("<select name=\"deletetype\">");
			if($result->num_rows == 0){
				print "Error: No Types. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($type = $result->fetch_assoc()){
					$i++;
					print "<option>" . $type["tname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete Type" />
	</form>
	
	<h3>Add/Remove Shapes</h3>
	<form action="admin.php" method="post">
		New Shape Name: <input type="text" name="newshapetype" />
		<input type="submit" value="Create Shape" /><br /><br />	
	</form>
			
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM ShapeTypes ORDER BY shapeid");
			print("<select name=\"deleteshapetype\">");
			if($result->num_rows == 0){
				print "Error: No Shapes. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($shapes = $result->fetch_assoc()){
					$i++;
					print "<option>" . $shapes["sname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete Shape" />
	</form>
	
	<h3>Create a new Furniture Piece</h3>
	<form action="admin.php" method="post">
		 Name: <input type="text" name="newpiecename" />* <br />
		 Model Number: <input type="text" name="newpiecemodelno" />* <br />
		 Description: <input type="text" name="newpiecedescription" />* <br />
		 Photo URL: <input type="text" name="newpiecephotourl" />* <br />
		 Dimensions (length x width x height):
		 <?php
		 print("<select name=\"newpiecelength\">");
		 for($i = 0; $i<=120; $i++){
			print "<option>" . $i . " in</option>";
		 }
		 print("</select>");
		 ?>
		 x
		 <?php
		 print("<select name=\"newpiecewidth\">");
		 for($i = 0; $i<=120; $i++){
			print "<option>" . $i . " in</option>";
		 }
		 print("</select>");
		 ?>
		 x
		 <?php
		 print("<select name=\"newpieceheight\">");
		 for($i = 0; $i<=120; $i++){
			print "<option>" . $i . " in</option>";
		 }
		 print("</select>");
		 ?>
		<br />
		Category:
		<?php
		$result = $mysqli->query("SELECT * FROM CategoryTypes ORDER BY categoryid");
		print("<select name=\"newpiececategorytype\">");
		if($result->num_rows == 0){
			print "Error: No Category Types. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($categories = $result->fetch_assoc()){
				$i++;
				print "<option>" . $categories["cname"] . "</option>";
			}
		}
		print("</select>");
		?>
		Type:
		<?php
		$result = $mysqli->query("SELECT * FROM Types ORDER BY typeid");
		print("<select name=\"newpiecetype\">");
		if($result->num_rows == 0){
			print "Error: No Types. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($types = $result->fetch_assoc()){
				$i++;
				print "<option>" . $types["tname"] . "</option>";
			}
		}
		print("</select>");
		?>
		Material:
		<?php
		$result = $mysqli->query("SELECT * FROM MaterialTypes ORDER BY materialid");
		print("<select name=\"newpiecematerialtype\">");
		if($result->num_rows == 0){
			print "Error: No Material Types. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($materials = $result->fetch_assoc()){
				$i++;
				print "<option>" . $materials["mname"] . "</option>";
			}
		}
		print("</select>");
		?>
		Finish:
		<?php
		$result = $mysqli->query("SELECT * FROM FinishTypes ORDER BY finishid");
		print("<select name=\"newpiecefinishtype\">");
		if($result->num_rows == 0){
			print "Error: No Finish Types. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($finishes = $result->fetch_assoc()){
				$i++;
				print "<option>" . $finishes["fname"] . "</option>";
			}
		}
		print("</select>");
		?>
		Shape:
		<?php
		$result = $mysqli->query("SELECT * FROM ShapeTypes ORDER BY shapeid");
		print("<select name=\"newpieceshapetype\">");
		if($result->num_rows == 0){
			print "Error: No Shapes. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($shapes = $result->fetch_assoc()){
				$i++;
				print "<option>" . $shapes["sname"] . "</option>";
			}
		}
		print("</select>");
		?>	 
		<br />
		<input type="submit" value="Create Piece" /><br /><br />	
	</form>
	
	<h3>Add/Remove Sets</h3>
	<form action="admin.php" method="post">
		New Set Name: <input type="text" name="newsetname" />
		New Set Category:
		<?php
		$result = $mysqli->query("SELECT * FROM CategoryTypes ORDER BY categoryid");
		print("<select name=\"newsetcategorytype\">");
		if($result->num_rows == 0){
			print "Error: No Category Types. Please add some.<br/>";
		}
		else{
			$i = 0;
			while($categories = $result->fetch_assoc()){
				$i++;
				print "<option>" . $categories["cname"] . "</option>";
			}
		}
		print("</select>");
		?>
		<input type="submit" value="Create Set" /><br /><br />	
	</form>
	<form action="admin.php" method="post">				
			<?php
			$result = $mysqli->query("SELECT * FROM Sets");
			print("<select name=\"deleteset\">");
			if($result->num_rows == 0){
				print "Error: No Sets. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($set = $result->fetch_assoc()){
					$i++;
					print "<option>" . $set["setname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Delete Set" />
	</form>	
	
	<h3>Modify Existing Sets</h3>
	<form action="admin.php" method="post">
		Set:				
			<?php
			$result = $mysqli->query("SELECT * FROM Sets");
			print("<select name=\"modifysettype\">");
			if($result->num_rows == 0){
				print "Error: No Sets. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($set = $result->fetch_assoc()){
					$i++;
					print "<option>" . $set["setname"] . "</option>";
				}
			}
			print("</select>");
			?>
		Piece:
			<?php
			$result = $mysqli->query("SELECT * FROM Pieces");
			print("<select name=\"addpiecetoset\">");
			if($result->num_rows == 0){
				print "Error: No Pieces. Please add some.<br/>";
			}
			else{
				$i = 0;
				while($piece = $result->fetch_assoc()){
					$i++;
					print "<option>" . $piece["pname"] . "</option>";
				}
			}
			print("</select>");
			?>
			<input type="submit" value="Add to Set" />
	</form>	

</div>

<?php
	//close the database connection
	$mysqli->close();

	//DEBUGGING/TESTING MESSAGE
	echo $message;
	include ('includes/footer.php');
?>
</body>
</html>